package nl.jjsoft.airlock.view.presenters.helpers
{
	import flash.events.IEventDispatcher;
	
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	
	import nl.jjsoft.airlock.controller.SafeController;
	import nl.jjsoft.airlock.domain.Model;
	import nl.jjsoft.airlock.event.AccountEvent;
	import nl.jjsoft.airlock.utils.ResourceFactory;
	import nl.jjsoft.airlock.vo.AccountVo;
	
	/**
	 * Helper class for account related functionality shared between presentations.
	 */
	public class AccountPresenterHelper
	{
		[Inject]
		public var model:Model;
		
		[Inject]
		public var safeController:SafeController;
		
		[Inject]
		public var resourceFactory:ResourceFactory;
		
		[Dispatcher]
		public var dispatcher:IEventDispatcher;
		
		private var accountDeleteConfirmDialog:Alert;
		
		public function AccountPresenterHelper()
		{
		}

		public function deleteAccount(account:AccountVo):void {
			if (account != null) {
				accountDeleteConfirmDialog = Alert.show(resourceFactory.getResource("shared.areyousure"), resourceFactory.getResource("accountform.removeaccount"), Alert.YES + Alert.NO, null, function close(event:CloseEvent):void {
					deleteAccountConfirmationClose(event, account);				
					event.target.removeEventListener(CloseEvent.CLOSE, arguments.callee);
				});				
			}
		}
		
		private function deleteAccountConfirmationClose(event:CloseEvent, selectedAccount:AccountVo):void {
			if (event.detail == Alert.YES) {
				if (safeController.deleteAccount(selectedAccount)) {
					model.selectedGroup.passwords.removeItemAt(model.selectedGroup.passwords.getItemIndex(selectedAccount));
					dispatcher.dispatchEvent(new AccountEvent(AccountEvent.HIDE_EDIT_FORM, true));
				}
			}
		} 
	}
}